<script setup lang="ts">
import { ref, onMounted, watch, computed, onUnmounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Search, Star, Close, MoreFilled } from "@element-plus/icons-vue";
import { LazyImg, Waterfall } from "vue-waterfall-plugin-next";
import "vue-waterfall-plugin-next/dist/style.css";
import { TravelNoteApi } from '@/api/new/travelNoteApi.js';
import { ElMessage } from 'element-plus';
import ArticleDetail from '@/components/ArticleDetail.vue';
import { UserProfileApi } from '@/api/new/userProfleApi.js';
import UserUtil from '@/utils/User/User.js';

const route = useRoute();
const router = useRouter();

// 搜索关键词
const searchKeyword = ref('');

// 文章列表
const list = ref([]);
const loading = ref(true);
const hasMore = ref(true);
const noResults = ref(false);
const searching = ref(false);

// 分页参数
const page = ref(1);
const pageSize = ref(20);

// 文章详情模态窗口状态
const showArticleDetail = ref(false);
const currentArticleId = ref(null);

// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png';

// 作者信息缓存
const authorCache = ref({});

// 收藏状态缓存 - 改为存储收藏ID而不仅是布尔值
const favoriteCache = ref({});

// 举报对话框相关状态
const reportDialogVisible = ref(false);
const reportReason = ref('');
const reportOtherReason = ref('');
const reportingArticleId = ref(null);

// 计算属性：是否可以提交举报
const canSubmitReport = computed(() => {
  if (!reportReason.value) return false;
  if (reportReason.value === '其他' && !reportOtherReason.value.trim()) return false;
  return true;
});

// 重置搜索 - 移到 watch 之前
const resetSearch = () => {
  page.value = 1;
  list.value = [];
  hasMore.value = true;
  noResults.value = false;
};

// 打开举报对话框
const openReportDialog = (article) => {
  // 阻止事件冒泡，避免触发卡片点击事件
  event.stopPropagation();

  // 检查用户是否登录
  if (!UserUtil.isLogin()) {
    ElMessage.warning('请先登录后再举报');
    return;
  }

  reportingArticleId.value = article.articleID;
  reportReason.value = '';
  reportOtherReason.value = '';
  reportDialogVisible.value = true;
};

// 关闭举报对话框
const handleReportDialogClose = () => {
  reportDialogVisible.value = false;
  reportReason.value = '';
  reportOtherReason.value = '';
  reportingArticleId.value = null;
};

// 提交举报
const submitReport = async () => {
  if (!canSubmitReport.value) return;

  try {
    // 准备举报原因
    const finalReason = reportReason.value === '其他'
      ? reportOtherReason.value
      : reportReason.value;

    // 调用举报API
    await TravelNoteApi.reportTravelNote(reportingArticleId.value, finalReason);

    ElMessage.success('举报已提交，感谢您的反馈');
    handleReportDialogClose();
  } catch (error) {
    console.error('举报失败:', error);
    ElMessage.error(`举报失败: ${error.message || '未知错误'}`);
  }
};

// 手动检查滚动位置
const checkScrollPosition = () => {
  // 如果已经没有更多数据或正在加载，则不处理
  if (loading.value || !hasMore.value) return;
  
  const scrollHeight = document.documentElement.scrollHeight;
  const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  const clientHeight = document.documentElement.clientHeight;
  
  // 如果滚动到距离底部100px以内，触发加载更多
  if (scrollHeight - scrollTop - clientHeight < 100) {
    loadMoreArticles();
  }
};

// 添加滚动事件监听
const addScrollListener = () => {
  window.addEventListener('scroll', checkScrollPosition);
};

// 移除滚动事件监听
const removeScrollListener = () => {
  window.removeEventListener('scroll', checkScrollPosition);
};

// 处理滚动到底部事件
const loadMoreArticles = () => {
  if (!loading.value && hasMore.value) {
    page.value++;
    searchArticles(false);
  }
};

// 跳转到用户个人页面
const goToUserProfile = (userId) => {
  if (!userId) return;
  router.push({
    path: '/otherUser',
    query: { userId }
  });
};

// 获取作者信息
const fetchAuthorInfo = async (authorId) => {
  // 如果缓存中已有该作者信息，直接返回
  if (authorCache.value[authorId]) {
    return authorCache.value[authorId];
  }
  
  try {
    // 使用 UserProfileApi 获取用户信息
    const userData = await UserProfileApi.getUserInfo(authorId);
    
    // 缓存作者信息
    authorCache.value[authorId] = {
      username: userData.username || '未知用户',
      headshot: userData.headshot || defaultAvatar
    };
    
    return authorCache.value[authorId];
  } catch (error) {
    // 返回默认信息
    return {
      username: '未知用户',
      headshot: defaultAvatar
    };
  }
};

// 检查用户是否已收藏文章
const checkFavoriteStatus = async (articleId) => {
  // 检查用户是否登录
  if (!UserUtil.isLogin()) {
    return { isFavorited: false, favoriteId: null };
  }
  
  // 获取当前用户ID
  const userId = UserUtil.getUserId();
  if (!userId) {
    return { isFavorited: false, favoriteId: null };
  }
  
  // 生成缓存键
  const cacheKey = `${userId}-${articleId}`;
  
  // 如果缓存中已有该收藏状态，直接返回
  if (favoriteCache.value[cacheKey] !== undefined) {
    return favoriteCache.value[cacheKey];
  }
  
  try {
    // 调用API检查收藏状态
    const Json_result = await TravelNoteApi.getFavoriteId(userId, articleId);
    const result = JSON.parse(Json_result);
    
    // 缓存收藏状态和ID
    const favoriteInfo = {
      isFavorited: result.status === "success",
      favoriteId: result.status === "success" ? result.favoriteID : null
    };

    favoriteCache.value[cacheKey] = favoriteInfo;

    return favoriteInfo;
  } catch (error) {
    return { isFavorited: false, favoriteId: null };
  }
};

// 切换收藏状态
const toggleFavorite = async (article) => {
  // 阻止事件冒泡，避免触发卡片点击事件
  event.stopPropagation();
  
  // 检查用户是否登录
  if (!UserUtil.isLogin()) {
    ElMessage.warning('请先登录');
    return;
  }
  
  try {
    const currentUserId = UserUtil.getUserId();
    const articleId = article.articleID;
    const cacheKey = `${currentUserId}-${articleId}`;
    
    if (article.isFavorited) {
      // 已收藏，需要取消收藏
      // 尝试从缓存获取收藏ID
      let favoriteId = favoriteCache.value[cacheKey]?.favoriteId;
      
      if (!favoriteId) {
        // 如果缓存中没有收藏ID，则从API获取
        const res = await TravelNoteApi.getFavoriteId(currentUserId, articleId);
        const response = JSON.parse(res);
        if (response && response.status === 'success') {
          favoriteId = response.favoriteID;
        } else {
          ElMessage.error('获取收藏ID失败');
          return;
        }
      }
      
      if (favoriteId) {
        // 使用收藏ID删除收藏记录
        const deleteResult = await TravelNoteApi.deleteCollection(favoriteId);
        
        // 更新UI
        article.isFavorited = false;
        if (article.favoriteCount > 0) {
          article.favoriteCount--;
        }
        
        // 更新缓存
        favoriteCache.value[cacheKey] = { isFavorited: false, favoriteId: null };
        
        ElMessage.success('取消收藏成功');
      } else {
        ElMessage.error('收藏ID不存在，无法取消收藏');
      }
    } else {
      // 未收藏，需要添加收藏
      const result = await TravelNoteApi.collectTravelNote(articleId);
      
      // 直接使用返回的字符串结果
      if (result && result.includes("游记收藏成功")) {
        // 更新UI
        article.isFavorited = true;
        article.favoriteCount = (article.favoriteCount || 0) + 1;
        
        // 更新缓存 - 由于没有返回favoriteID，下次需要重新获取
        favoriteCache.value[cacheKey] = { 
          isFavorited: true, 
          favoriteId: null  // 这里设为null，因为API没有返回favoriteID
        };
        
        ElMessage.success('收藏成功');
      } else {
        ElMessage.error('收藏失败');
      }
    }
  } catch (error) {
    ElMessage.error(`操作失败: ${error.message || '未知错误'}`);
  }
};

// 搜索游记
const searchArticles = async (isFirstSearch = true) => {
  if (!searchKeyword.value.trim()) return;

  try {
    loading.value = true;
    searching.value = true;

    // 调用搜索游记API
    const response = await TravelNoteApi.searchTravelNotes(searchKeyword.value, page.value, pageSize.value);

    // 检查响应格式
    if (!Array.isArray(response)) {
      ElMessage.error('获取搜索结果失败：数据格式错误');
      loading.value = false;
      searching.value = false;
      return;
    }

    // 如果没有搜索结果
    if (response.length === 0) {
      if (isFirstSearch) {
        noResults.value = true;
        list.value = [];
      } else {
        hasMore.value = false;
      }
      loading.value = false;
      searching.value = false;
      return;
    }

    // 如果返回的数据少于请求的数量，说明这是最后一页
    if (response.length < pageSize.value) {
      hasMore.value = false;
    }

    // 处理每篇游记，获取其图片、作者信息和收藏状态
    const articlesWithDetails = await Promise.all(
      response.map(async (article) => {
        try {
          // 并行获取图片、作者信息和收藏状态
          const [imageData, authorInfo, favoriteInfo] = await Promise.all([
            TravelNoteApi.getFirstImage(article.articleID),
            fetchAuthorInfo(article.authorID),
            checkFavoriteStatus(article.articleID)
          ]);
          
          // 处理图片URL
          let imageUrl = null;
          if (imageData) {
            if (typeof imageData === 'string') {
              try {
                const parsedImage = JSON.parse(imageData);
                imageUrl = parsedImage.imageUrl;
              } catch (e) {
                imageUrl = imageData;
              }
            } else if (imageData.imageUrl) {
              imageUrl = imageData.imageUrl;
            }
          }
          
          // 构建完整的文章对象
          return {
            ...article,
            imageUrl: imageUrl || getDefaultImageUrl(),
            authorName: authorInfo.username,
            authorAvatar: authorInfo.headshot,
            isFavorited: favoriteInfo.isFavorited,
            favoriteId: favoriteInfo.favoriteId
          };
        } catch (error) {
          return {
            ...article,
            imageUrl: getDefaultImageUrl(),
            authorName: '未知用户',
            authorAvatar: defaultAvatar,
            isFavorited: false,
            favoriteId: null
          };
        }
      })
    );

    // 更新列表
    if (isFirstSearch) {
      list.value = articlesWithDetails;
    } else {
      // 追加新加载的文章
      list.value = [...list.value, ...articlesWithDetails];
    }

    // 如果没有结果，显示无结果提示
    noResults.value = list.value.length === 0;

  } catch (error) {
    console.error("搜索游记失败：", error);
    ElMessage.error(`搜索游记失败：${error.message || '未知错误'}`);
  } finally {
    loading.value = false;
    searching.value = false;
  }
};

// 监听路由参数变化
watch(() => route.query.keyword, (newKeyword) => {
  if (newKeyword) {
    searchKeyword.value = newKeyword as string;
    resetSearch();
    searchArticles(true);
  }
}, { immediate: true });

// 清空搜索
const clearSearch = () => {
  searchKeyword.value = '';
  resetSearch();
};

// 执行搜索
const handleSearch = () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词');
    return;
  }
  
  // 更新URL参数但不重新加载页面
  router.push({
    query: { 
      ...route.query,
      keyword: searchKeyword.value 
    }
  });
  
  resetSearch();
  searchArticles(true);
};

// 打开文章详情
const openArticleDetail = (articleId) => {
  currentArticleId.value = articleId;
  showArticleDetail.value = true;
  // 禁止背景滚动
  document.body.style.overflow = 'hidden';
};

// 关闭文章详情
const closeArticleDetail = () => {
  showArticleDetail.value = false;
  // 恢复背景滚动
  document.body.style.overflow = '';
};

// 获取默认图片URL
const getDefaultImageUrl = () => {
  return 'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png';
};

// 页面加载和卸载事件
onMounted(() => {
  // 添加滚动事件监听器
  addScrollListener();
});

onUnmounted(() => {
  // 移除滚动事件监听器
  removeScrollListener();
});
</script>

<template>
  <div class="search-page">
    <div class="search-header">
      <div class="search-info">
        <h2>搜索结果: {{ searchKeyword }}</h2>
        <p v-if="!loading && list.length > 0">找到 {{ list.length }} 条相关游记</p>
      </div>
    </div>

    <div class="search-results">
      <div v-if="loading && page === 1" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <div v-else-if="noResults" class="no-results">
        <el-empty description="没有找到相关游记" />
      </div>
      
      <Waterfall 
        v-else 
        :list="list" 
        :width="240" 
        :hasAroundGutter="false" 
        style="max-width: 1260px"
        @scroll-reach-bottom="loadMoreArticles"
      >
        <template #item="{ item }">
          <div class="card">
            <!-- 使用 LazyImg 组件加载图片 -->
            <LazyImg
              :url="item.imageUrl || getDefaultImageUrl()"
              style="border-radius: 8px"
              @click="openArticleDetail(item.articleID)"
            />

            <div class="footer">
              <!-- 显示标题 -->
              <a class="title"><span>{{ item.title }}</span></a>

              <div class="author-wrapper">
                <!-- 显示作者信息 -->
                <a class="author" @click.stop="goToUserProfile(item.authorID)">
                  <img class="author-avatar" :src="item.authorAvatar || defaultAvatar" />
                  <span class="name">{{ item.authorName || '未知用户' }}</span>
                </a>

                <!-- 操作按钮区域 -->
                <div class="action-buttons">
                  <!-- 收藏按钮 -->
                  <span 
                    class="like-wrapper" 
                    :class="{ 'like-active': item.isFavorited }"
                    @click.stop="toggleFavorite(item)"
                  >
                    <Star style="width: 1em; height: 1em" />
                    <span class="count">{{ item.favoriteCount || 0 }}</span>
                  </span>
                  
                  <!-- 举报按钮 -->
                  <span class="more-options" @click.stop="openReportDialog(item)">
                    <el-icon><MoreFilled /></el-icon>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </template>
      </Waterfall>
      
      <!-- 加载更多指示器 -->
      <div v-if="loading && page > 1" class="loading-more">
        <el-skeleton :rows="1" animated />
      </div>
      
      <!-- 没有更多数据提示 -->
      <div v-if="!loading && !hasMore && list.length > 0" class="no-more-data">
        没有更多内容了
      </div>
    </div>

    <!-- 文章详情模态窗口 -->
    <div v-if="showArticleDetail" class="article-modal-overlay" @click.self="closeArticleDetail">
      <ArticleDetail 
        :article-id="currentArticleId" 
        @close="closeArticleDetail"
      />
    </div>
    
    <!-- 举报对话框 -->
    <el-dialog
      v-model="reportDialogVisible"
      title="举报内容"
      width="30%"
      :before-close="handleReportDialogClose"
    >
      <div class="report-dialog-content">
        <p>请选择举报原因：</p>
        <el-radio-group v-model="reportReason" class="report-reason-group">
          <el-radio label="垃圾广告">垃圾广告</el-radio>
          <el-radio label="色情低俗">色情低俗</el-radio>
          <el-radio label="违法有害">违法有害</el-radio>
          <el-radio label="人身攻击">人身攻击</el-radio>
          <el-radio label="侵犯权益">侵犯权益</el-radio>
          <el-radio label="其他">其他</el-radio>
        </el-radio-group>
        
        <div v-if="reportReason === '其他'" class="report-other-reason">
          <el-input
            v-model="reportOtherReason"
            type="textarea"
            placeholder="请详细描述举报原因"
            maxlength="200"
            show-word-limit
            :rows="3"
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleReportDialogClose">取消</el-button>
          <el-button type="primary" @click="submitReport" :disabled="!canSubmitReport">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">
.search-page {
  padding: 16px 24px;
  
  .search-header {
    margin-bottom: 24px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 16px;
    
    .search-info {
      h2 {
        font-size: 24px;
        font-weight: 600;
        margin-bottom: 8px;
      }
      
      p {
        color: #666;
        font-size: 14px;
      }
    }
  }
  
  .search-results {
    .loading-container {
      padding: 20px;
      max-width: 1200px;
      margin: 0 auto;
    }
    
    .no-results {
      padding: 40px 0;
      text-align: center;
    }
    
    .loading-more {
      padding: 20px;
      text-align: center;
    }
    
    .no-more-data {
      padding: 20px;
      text-align: center;
      color: #999;
      font-size: 14px;
    }
    
    .card {
      margin-bottom: 16px;
      border-radius: 8px;
      overflow: hidden;
      background-color: #fff;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      transition: transform 0.3s;
      cursor: pointer;
      
      &:hover {
        transform: translateY(-5px);
      }
      
      .footer {
        padding: 12px;
        
        .title {
          margin-bottom: 8px;
          word-break: break-all;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
          font-weight: 500;
          font-size: 14px;
          line-height: 140%;
          color: #333;
        }
        
        .author-wrapper {
          display: flex;
          align-items: center;
          justify-content: space-between;
          height: 20px;
          color: rgba(51, 51, 51, 0.8);
          font-size: 12px;
          transition: color 1s;
          
          .author {
            display: flex;
            align-items: center;
            color: inherit;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-right: 12px;
            
            .author-avatar {
              margin-right: 6px;
              width: 20px;
              height: 20px;
              border-radius: 20px;
              border: 1px solid rgba(0, 0, 0, 0.08);
              flex-shrink: 0;
            }
            
            .name {
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }
          
          .action-buttons {
            display: flex;
            align-items: center;
            gap: 12px;
            
            .like-wrapper {
              position: relative;
              cursor: pointer;
              display: flex;
              align-items: center;

              .count {
                margin-left: 2px;
              }
            }
            
            .like-active {
              color: #ff2442;
            }
            
            .more-options {
              cursor: pointer;
              display: flex;
              align-items: center;
              padding: 2px;
              
              &:hover {
                color: #1890ff;
              }
            }
          }
        }
      }
    }
  }
}

// 添加模态窗口样式
.article-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.5); // 半透明黑色背景
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: auto;
}

// 举报对话框样式
.report-dialog-content {
  p {
    margin-bottom: 16px;
    font-weight: bold;
  }
  
  .report-reason-group {
    display: grid;
    grid-template-columns: repeat(2, 1fr); // 两列布局
    grid-gap: 15px 20px; // 行间距15px，列间距20px
    
    @media (min-width: 768px) {
      grid-template-columns: repeat(3, 1fr); // 在大屏上用三列布局
    }
  }
  
  .report-other-reason {
    margin-top: 16px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

// 自定义Element Plus对话框样式
:deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  
  .el-dialog__header {
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;
  }
  
  .el-dialog__body {
    padding: 24px;
  }
  
  .el-dialog__footer {
    padding: 16px 24px;
    border-top: 1px solid #f0f0f0;
  }
}

// 自定义Element Plus单选框样式
:deep(.el-radio) {
  margin-right: 0;
  padding: 8px 12px;
  border-radius: 8px;
  transition: all 0.3s;
  
  &:hover {
    background-color: #f5f7fa;
  }
  
  .el-radio__input.is-checked + .el-radio__label {
    font-weight: bold;
  }
}

// 自定义文本输入框样式
:deep(.el-textarea) {
  .el-textarea__inner {
    border-radius: 8px;
    transition: all 0.3s;
    
    &:focus {
      box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
    }
  }
}

// 自定义按钮样式
:deep(.el-button) {
  border-radius: 8px;
  
  &.el-button--primary {
    box-shadow: 0 2px 6px rgba(24, 144, 255, 0.2);
  }
}
</style>